import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Input, notification } from 'antd';
import type { MutableRefObject } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { join } from '@tauri-apps/api/path';
import type { Rsync } from '@fill/client';
import { client, queryClient, rspc } from '@fill/client';
import keyBy from 'lodash.keyby';
import dayjs from 'dayjs';
import { invoke } from '@tauri-apps/api';
import { FillContext } from '../app/Fill';
import { downloadPath } from '../../util';
import { CONFIG_KEYS } from '../../constants/config';
import { useImport } from '../record/Import';

export interface IRsyncProps {
  id: string
  fileName: string
  createTime: string
  onCallback: () => Promise<void>
}

export const ExportSync: React.FC<IRsyncProps> = (record) => {
  const {
    config,
    setLoading,
    setLoadingText,
  } = useContext(FillContext);

  const {
    handleImport,
  } = useImport();

  const download = async () => {
    const serve = config[CONFIG_KEYS.SERVER][0];
    setLoading(true);
    setLoadingText('下载中');
    // 下载
    const file_name = await join(await downloadPath(), record.fileName);
    console.log(`下载 - ${record.fileName} - ${file_name} 开始`);

    try {
      setLoadingText('写入下载');
      // await (async () => {
      //   const { data } = await axios.get(`/dataPacket/transfer/download/${record.id}`, {
      //     baseURL: import.meta.env.MODE === 'development' ? '' : `http://${serve.F_IP_}`,
      //     responseType: 'blob',
      //   });

      //   const reader = new FileReader();

      //   reader.onload = async function () {
      //     await writeBinaryFile(file_name, this.result as ArrayBuffer);
      //   };

      //   reader.readAsArrayBuffer(data);
      // })();
      const ids = new Uint32Array(1);
      window.crypto.getRandomValues(ids);
      const id = ids[0];

      await invoke('plugin:upload|download', {
        id,
        url: `http://${serve.F_IP_}/api/api-ida/dataPacket/transfer/download/${record.id}`,
        filePath: file_name,
        headers: {
          'Content-Type': 'application/json',
        },
      });

      console.log(`下载 - ${record.fileName}} - ${file_name} 完成`);
    }
    catch (error) {
      setLoading(false);
      notification.error({
        message: '下载失败',
      });
      console.log(error);
      console.log(`下载 - ${record.fileName}} - ${file_name} 失败`);
      return;
    }

    setLoadingText('插入记录');
    // 插入记录
    await queryClient.fetchQuery({
      queryKey: ['sync.save'],
      queryFn: () => client.mutation(['rsyncs.save', {
        arg: {
          id: record.id,
          name: file_name,
        },
      }]),
    });

    record.onCallback && await record.onCallback();

    // 执行导入
    setLoadingText('开始导入');

    try {
      await handleImport(file_name);
    }
    catch (error) {
      console.log(error);
    }

    setLoading(false);
  };

  return (
    <a
      key="editable"
      onClick={download}
    >
      导入
    </a>
  );
};

export const useSync = (actionRef: MutableRefObject<ActionType | undefined>) => {
  const { data, refetch } = rspc.useQuery(['rsyncs.all', { arg: null }]);

  const [mapRsync, setMapRsync] = useState<{ [key: string]: Rsync }>({});

  useEffect(() => {
    const rsyncCollection = keyBy(data, 'id');
    setMapRsync(rsyncCollection);
  }, [data]);

  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      width: 48,
    },
    {
      title: '文件',
      dataIndex: 'fileName',
      renderFormItem: (_, props) => {
        return <Input
          allowClear
          placeholder="文件名称"
          {...props}
        />;
      },
    },
    {
      title: '文件上传时间',
      key: 'showTime',
      dataIndex: 'createTime',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '文件获取时间',
      dataIndex: 'created_at',
      render(_dom, entity) {
        return <>
          {mapRsync[entity.id]?.created_at ? dayjs(mapRsync[entity.id]?.created_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
        </>;
      },
    },
    {
      title: '导入时间',
      dataIndex: 'created_at',
      hideInSearch: true,
      render(_dom, entity) {
        return <>
          {mapRsync[entity.id]?.imported_at ? dayjs(mapRsync[entity.id]?.imported_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
        </>;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_text, record) => [
        <ExportSync key="import" {...record} onCallback={async () => {
          await refetch();
          actionRef.current?.reload();
        }} />,
      ],
    },
  ];

  return {
    columns,
  };
};
